package com.qinghua.blog.controller.admin;

import com.qinghua.blog.po.User;
import com.qinghua.blog.service.UserService;
import com.qinghua.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("admin")
public class LoginController {

    @Autowired
    UserService userService;

    /**
     * 跳转到登录页面
     * @return
     */
    @GetMapping("/showLogin")
    public String showLogin(){

        return "admin/login";

    }

    /**
     * 根据用户名和方法验证登录
     * @param username
     * @param password
     * @param session
     * @param attributes
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, RedirectAttributes attributes){
        User user=userService.checkUser(username,MD5Utils.code(password));
        System.out.println(username+","+password);
        if(user!=null){
            user.setPassword(null);
            session.setAttribute("user",user);

            return "redirect:/admin/blogs";

        }
        attributes.addFlashAttribute("msg","用户名或密码错误");
        return "redirect:admin/showLogin";
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @GetMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.setAttribute("user",null);
        return "redirect:/";
    }
}
